package com.star.repsonse;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.star.utils.BaseConstants;
import com.star.utils.RestResult;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.AsyncHandlerMethodReturnValueHandler;
import org.springframework.web.method.support.HandlerMethodReturnValueHandler;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletResponse;

/**
 * @Author chaoyang
 * @Description: 自定义返回转换器 ,可以返回controller 方法 任意类型。
 * @Date 2019/8/28 0028
 * @Version V1.0
 **/
public class CustomResponseReturnValueHandler implements HandlerMethodReturnValueHandler, AsyncHandlerMethodReturnValueHandler {

    private static final ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public boolean isAsyncReturnValue(Object o, MethodParameter methodParameter) {
        return supportsReturnType(methodParameter);
    }

    @Override
    public boolean supportsReturnType(MethodParameter methodParameter) {

        return methodParameter.getAnnotatedElement().getAnnotation(RequestMapping.class) != null;
    }

    @Override
    public void handleReturnValue(Object body, MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest) throws Exception {
        modelAndViewContainer.setRequestHandled(true);
        HttpServletResponse response = nativeWebRequest.getNativeResponse(HttpServletResponse.class);
        response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
        if (body instanceof RestResult)
            response.getWriter().write(objectMapper.writeValueAsString(body));

        final RestResult result = new RestResult.RestResultBuilder()
                .code(BaseConstants.SUCCESS_CODE)
                .data(body)
                .success(BaseConstants.SUCCESS).builder();

        response.getWriter()
                .write(objectMapper.writeValueAsString(result));
    }
}
